package server;

import entry.Member;
import entry.MemberSocket;
import entry.Room;

import java.util.HashMap;

public class RoomManager {
    private HashMap<String, Room> rooms;
    //单例化
    private RoomManager(){ rooms = new HashMap<>();}
    private static final RoomManager roomManager = new RoomManager();
    public static RoomManager getRoomManager() {
        return roomManager;
    }

    public boolean hasRoom(MemberSocket member){
        if (rooms.containsKey(member.getMember().getID()))
            return true;
        return false;
    }

    public Room getRoom(MemberSocket member){
        return rooms.get(member.getMember().getID());
    }

    public Room getRoom(String ID){
        return rooms.get(ID);
    }

    public Room add(MemberSocket memberSocket){
        Room room = new Room();
        Member member = new Member(memberSocket.getMember().toString());
        room.setHostName(member.getUsername());
        room.setID(member.getID());
        room.addMember(memberSocket);
        room.setName(member.getUsername()+"的房间");
        rooms.put(room.getID(),room);
        return room;
    }

    public Room findRoom(MemberSocket memberSocket){
        Room room = null;
        for (String roomID:rooms.keySet()) {
            room = getRoom(roomID);
            for (MemberSocket m:room.getMembers().keySet()) {
                if (m.getMember().getID()==memberSocket.getMember().getID())
                    return room;
            }
        }
        return null;
    }

    public HashMap<String, Room> getRooms() {
        return rooms;
    }

    public void publish(MemberSocket memberSocket, String line){
        Room room = findRoom(memberSocket);
        for (MemberSocket other:room.getMembers().keySet()){
            if (other!=memberSocket)
                other.out(line);
        }
    }
}
